package com.hackcloud.shardingjdbc.config;

import com.hackcloud.shardingjdbc.service.IdWorker;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.IdentityGenerator;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.io.Serializable;

@Component
public class CustomerGenerator extends IdentityGenerator implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public Serializable generate(SessionImplementor s, Object obj) {
        IdWorker idWorker = applicationContext.getBean(IdWorker.class);
        long id = idWorker.nextId();
        return id;
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }
}
